<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;

class TrendsTopic extends Base
{
    protected $table = 'trends_topic';
    protected $primaryKey = 'topic_id';
    protected $tableSql = ['topic_id', 'topic_name', 'topic_desc', 'topic_image', 'topic_type', 'url'];

    protected $trendsTopicJoinTable = 'trends_topic_join';
    protected $trendContentTable = 'trends_content';

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 获取动态话题（支持获取用户创建的话题）
     *
     * @param string $keywords 关键字
     * @param int $page 页数 默认0
     * @param int $limit 条数 默认10
     * @return array
     * */
    public function getTrendsTopic($keywords = '', $page = 0, $limit = 10)
    {
        $condition = [
            ['topic_state', '=', 1]
        ];
        if (!empty($keywords)) {
            $condition[] = ['topic_name', 'like', "%$keywords%"];
        }

        $db = DB::table($this->table)->where($condition);

        // 总条数
        $totalCount = $db->count($this->primaryKey);

        // 获取话题数据
        $data = $db->offset($page * $limit)->limit($limit)->orderBy('sort', 'desc')->get($this->tableSql)->toArray();
        $data = self::objToArray($data);

        // 获取话题对应动态总数
        $getTopicIdCountData = [];
        if (!empty($data)) {
            $topicIds = array_unique(array_column($data, 'topic_id'));
            $getTopicIdCountData = DB::table($this->trendsTopicJoinTable)->whereIn('topic_id', $topicIds)->groupBy('topic_id')->select('topic_id', DB::raw('count(topic_id) as total_count'))->get()->toArray();
            $getTopicIdCountData = self::objToArray($getTopicIdCountData);
        }

        $topicIdKeyArray = array_column($getTopicIdCountData, 'topic_id', 'topic_id');
        $topicIdArray = array_values($topicIdKeyArray);

        foreach ($data as $key => $value) {
            $data[$key]['topic_image'] = build_image($value['topic_image']);

            $data[$key]['trends_count'] = 0;
            if (array_key_exists($value['topic_id'], $topicIdKeyArray)) {
                $topicIdIndex = array_search($value['topic_id'], $topicIdArray);
                $data[$key]['trends_count'] = $getTopicIdCountData[$topicIdIndex]['total_count'];
            }
        }

        return $this->checkPageData($page, $limit, $totalCount, $data);
    }

    /**
     * 动态话题-获取详情
     * @param int $topicId 动态话题ID
     * @return array
     * */
    public function getTrendsTopicDetail($topicId)
    {
        $data = DB::table($this->table)->where([$this->primaryKey => $topicId])->first($this->tableSql);
        $data = self::objToArray($data);
        if (empty($data)) {
            $data = [];
        }

        $data['topic_image'] = build_image($data['topic_image']);

        return $data;
    }

    /**
     * 动态话题-创建/更新
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新
     * @param int $topicId 动态话题ID
     * @return bool
     * */
    public function CUDTrendsTopic($data = [], $type = 'insert', $topicId = 0)
    {
        $timestamp = time();

        switch ($type) {
            case 'insert':
                $data['created_at'] = $timestamp;
                $data['updated_at'] = $timestamp;
                $ret = DB::table($this->table)->insertGetId($data);
                break;
            case 'update':
                $data['updated_at'] = $timestamp;
                $ret = DB::table($this->table)->where([$this->primaryKey => $topicId])->update($data);
                break;
            case 'delete':
                $ret = DB::table($this->table)->where([$this->primaryKey => $topicId])->delete();
                break;
            default:
                $ret = false;
                break;
        }

        return $ret;
    }

    /**
     * 根据话题ID获取动态话题
     *
     * @param array $topicIds 话题ID组
     * @return array
     * */
    public function getTrendsTopicById($topicIds)
    {
        $data = DB::table($this->table)->whereIn('topic_id', $topicIds)->get($this->tableSql)->toArray();
        $data = self::objToArray($data);

        foreach ($data as $key => $value) {
            $data[$key]['topic_image'] = build_image($value['topic_image']);
        }

        return $data;
    }

    ####################################################################################################

    /**
     * 动态话题-动态参与-获取动态内容列表分页
     *
     * @param int $topicId 动态话题ID
     * @param int $page 页数 默认0
     * @param int $limit 条数 默认10
    * @param int $examine_switch 审核开关 1开启 0关闭
     * @return array
     * */
    public function getTrendsJoinByTopicId($topicId, $page = 0, $limit = 10 ,$examine_switch=0)
    {
        //101 需求改版前
//        $db = DB::table($this->trendsTopicJoinTable)->where([$this->primaryKey => $topicId])->orderBy("id", "desc");
//
//        // 总条数
//        $totalCount = $db->count($this->primaryKey);
//
//        // 查询数据
//        $list = $db->offset($page * $limit)->limit($limit)->get()->toArray();
//        $list = self::objToArray($list);
        if($examine_switch == 1){
            $db = DB::table($this->trendsTopicJoinTable)
                ->leftJoin($this->trendContentTable, 'trends_topic_join.content_id', '=', 'trends_content.content_id')
                ->where([$this->primaryKey => $topicId])
                ->where('trends_content.create_timestamp','>',1614528000)
                ->orderBy("content_type", "desc")
                ->orderBy("trends_content.content_id", "desc");
        }else{
            //101 需求改版后
            $db = DB::table($this->trendsTopicJoinTable)
                ->leftJoin($this->trendContentTable, 'trends_topic_join.content_id', '=', 'trends_content.content_id')
                ->where([$this->primaryKey => $topicId])
                ->orderBy("content_type", "desc")
                ->orderBy("trends_content.content_id", "desc");
        }

        // 总条数
        $totalCount = $db->count($this->primaryKey);

        // 查询数据
        $list = $db->offset($page * $limit)->limit($limit)->get(["{$this->trendsTopicJoinTable}.*","{$this->trendContentTable}.type as content_type"])->toArray();
        $list = self::objToArray($list);

        return $this->checkPageData($page, $limit, $totalCount, $list);
    }

    /**
     * 动态话题-动态参与-创建/更新
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新
     * @param int $contentId 动态内容ID
     * @param int $topicId 动态话题ID
     * @return bool
     * */
    public function CUDTrendsTopicJoin($data = [], $type = 'insert', $contentId = 0, $topicId = 0)
    {
        // 更新、删除条件
        if (in_array($type, ['update', 'delete'])) {
            if ($contentId > 0 and $topicId > 0) {
                $condition[$this->primaryKey] = $topicId;
            } elseif ($contentId > 0) {
                $condition = ['content_id' => $contentId];
            } elseif ($topicId > 0) {
                $condition = [$this->primaryKey => $topicId];
            } else {
                $condition = [];
            }
        }

        switch ($type) {
            case 'insert':
                $data['created_at'] = time();
                $ret = DB::table($this->trendsTopicJoinTable)->insertGetId($data);
                break;
            case 'insertBatch':
                $ret = DB::table($this->trendsTopicJoinTable)->insert($data);
                break;
            case 'update':
                if (empty($condition)) {
                    $ret = false;
                    break;
                }
                $ret = DB::table($this->trendsTopicJoinTable)->where($condition)->update($data);
                break;
            case 'delete':
                if (empty($condition)) {
                    $ret = false;
                    break;
                }
                $ret = DB::table($this->trendsTopicJoinTable)->where($condition)->delete();
                break;
            default:
                $ret = false;
                break;
        }

        return $ret;
    }

    /**
     * 根据动态ID-获取话题
     *
     * @param array $contentIds 动态ID组
     * @return array
     * */
    public function getTrendsTopicDataByContentIds($contentIds)
    {
        # 一对一
        /*$data = DB::table($this->trendsTopicJoinTable)
            ->leftJoin($this->table, $this->trendsTopicJoinTable . '.topic_id', '=', $this->table . '.topic_id')
            ->whereIn($this->trendsTopicJoinTable . '.content_id', $contentIds)
            ->where($this->table . '.topic_state', '=', 1)
            ->get([
                $this->trendsTopicJoinTable . '.content_id',
                $this->table . '.topic_id',
                $this->table . '.topic_name',
                $this->table . '.topic_desc',
                $this->table . '.topic_image',
                $this->table . '.topic_type',
                $this->table . '.url',
            ])->toArray();
        return self::objToArray($data);*/

        # 一对多

        $topicData = [];

        do {
            $trendTopicJoin = DB::table($this->trendsTopicJoinTable)->whereIn('content_id', $contentIds)->get(['topic_id', 'content_id'])->toArray();
            $trendTopicJoin = self::objToArray($trendTopicJoin);
            if (empty($trendTopicJoin)) {
                break;
            }

            $trendTopicIds = array_unique(array_column($trendTopicJoin, 'topic_id'));
            $trendTopic = DB::table($this->table)->where(['topic_state' => 1])->whereIn('topic_id', $trendTopicIds)->get($this->tableSql)->toArray();
            $trendTopic = self::objToArray($trendTopic);
            if (empty($trendTopic)) {
                break;
            }

            $trendTopicIdKeyArray = array_column($trendTopic, 'topic_id', 'topic_id');
            $trendTopicIdArray = array_values($trendTopicIdKeyArray);

            foreach ($trendTopicJoin as $key => $value) {
                if (!array_key_exists($value['topic_id'], $trendTopicIdKeyArray)) {
                    continue;
                }

                $trendTopicIdIndex = array_search($value['topic_id'], $trendTopicIdArray);

                $trendTopic[$trendTopicIdIndex]['content_id'] = $value['content_id'];
                $topicData[] = $trendTopic[$trendTopicIdIndex];
            }

            $topicData = dataGroup($topicData, 'content_id');

        } while (false);

        return $topicData;
    }

}